package com.shanghaionstar.utils;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

import com.onstar.cn.auth.AuthTokenRequestEntity;
import com.onstar.cn.auth.userProfile.Subscriber;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.mvp.base.core.AppScheduler;
import com.onstar.cn.framework.network.ClientTraceInstance;
import com.onstar.cn.framework.utils.GsonHelper;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.rxconstants.RxConstants;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.login.AuthorizeReceiver;
import com.shanghaionstar.login.service.AuthorService;
import com.shanghaionstar.login.service.LoginSerice;
import com.shanghaionstar.login.service.LoginTransformHelper;
import com.shanghaionstar.notification.service.NotificationControl;

import java.util.Calendar;

import rx.Observable;
import rx.functions.Action1;

/**
 * Created by 6335yz on 2016/6/29.
 */
public class AuthorUtil {

    //do not login out when doing the alarm;
    public boolean isLoginOut = false;

    public void setIsLoginOut(boolean isLogin) {
        this.isLoginOut = isLogin;
    }

    public static AuthorUtil getInstance() {
        return Inner.authorUtil;
    }

    static class Inner {
        static final AuthorUtil authorUtil = new AuthorUtil();
    }

    public void loginOut(Context context) {
        loginOutData(context);

        RxBus.getDefault().post(RxConstants.ALL_PAGE_REFRESH, RxConstants.LOGIN_OUT);
    }

    //    private void deleteToken(Context context) {
//        ApiManager.getInstance(context)
//                .getLoginApi()
//                .deleteToken(true)
//                .subscribeOn(new AppScheduler().backgroundThread())
//                .observeOn(new AppScheduler().mainThread())
//                .subscribe(new Action1<String>() {
//                   @Override
//                   public void call(String s) {
//                       LogManager.getInstance().d("delete token success --->>"+s);
//                   }
//               }, new Action1<Throwable>() {
//                   @Override
//                   public void call(Throwable throwable) {
//                       LogManager.getInstance().d("delete token fail --->>"+throwable.getMessage());
//                   }
//               });
//    }
    public void loginOutData(Context context) {
        new LoginSerice(context).deleteToken(true)
                .subscribeOn(new AppScheduler().backgroundThread())
                .observeOn(new AppScheduler().mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String response) {
                        LogManager.getInstance().d("delete token success --->>" + response);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogManager.getInstance().d("delete token fail --->>" + throwable.getMessage());
                    }
                });
        // 取消polling
        BusinessUtil.refreshPolling(context);
        BusinessUtil.clearOnstarAppContext(context);

        BusinessUtil.loadConfig(context);

//        BusinessUtil.updateConfigValue(FinalConfigParams.LOG_OUT, FinalConfigParams.TRUE, context);
        PreferencesUtls.getInstance(context).putBoolean(FinalConfigParams.LOG_OUT, true);

        /**
         * 存放token
         */
        PreferencesUtls.getInstance(context).putString(Constants.ID_TOKEN, "");
        PreferencesUtls.getInstance(context).putString(Constants.ACCESS_TOKEN, "");

        /**
         * 存放token时间
         */
        PreferencesUtls.getInstance(context).putString(Constants.TIME_ID_TOKEN, "");
        PreferencesUtls.getInstance(context).putString(Constants.TIME_LOCAL_TOKEN, "");

        /**
         * 清除车辆feature缓存
         */
        PreferencesUtls.getInstance(context).putString(Constants.AUTH_USER_FEATURE, "");

        /**
         * 清除profile
         */
        PreferencesUtls.getInstance(context).putString(Constants.AUTH_USER_PROFILE, "");

        /**
         * 清除自动登录状态
         */
        OnstarApplication.getApplication().setmLoginState(LoginTransformHelper.CACHE_STATE_NONE);

        // 取消定时刷新token。
        cancelRegistAlarmReauthentication(context);
        NotificationControl.getInstants(context).saveDeviceInfo(ApplicationUtil.getInstance().isLogin());

        BusinessUtil.clearOnstarAppContext(context);
        ClientTraceInstance.getInstance().setIdpId(null);

//        RxBus.getDefault().post(RxConstants.ALL_PAGE_REFRESH, RxConstants.LOGIN_OUT);
    }

    public void finisLogin(Context context) {
        BusinessUtil.refreshPolling(context);
        OnstarApplication application = (OnstarApplication) (context.getApplicationContext());
        ApplicationUtil.getInstance().setLogin(true);
        BusinessUtil.updateConfigValue(FinalConfigParams.UPDATE_BANNER, FinalConfigParams.TRUE, context);
        BusinessUtil.updateConfigValue(FinalConfigParams.ISLOADDATAS, FinalConfigParams.TRUE, context);

        BusinessUtil.autoRefresh(context);

        String userProfileJson = PreferencesUtls.getInstance(context).getString(
                Constants.AUTH_USER_PROFILE);
        Subscriber subscriber = GsonHelper.fromJson(userProfileJson, Subscriber.class);
        BusinessUtil.sendReportByClickType(context, com.shanghaionstar.enumtype.FunctionNameFindId.loginregister_Login.getStringValue());
        BusinessUtil.saveSessionAfterLogin(context, subscriber);

        if (ApplicationUtil.getInstance().isExpiredSubscriber()) {
            context.sendBroadcast(new Intent(Constants.BROADCAST_OVERDUE));
        }
        cancelRegistAlarmReauthentication(context);
        registAlarmReauthentication(context);
    }

    public void registAlarmReauthentication(Context context) {
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, AuthorizeReceiver.class);
        intent.setAction(Constants.AUTHORIZE_REFRESH_TOKEN);

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());

        calendar.add(Calendar.MILLISECOND, Constants.TIME_ALARM_TOKEN);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1, intent, 0);
        alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
    }

    public void cancelRegistAlarmReauthentication(Context context) {
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, AuthorizeReceiver.class);
        intent.setAction(Constants.AUTHORIZE_REFRESH_TOKEN);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1, intent, 0);
        alarmManager.cancel(pendingIntent);
    }


    public void reauthForNoPin(Context context, Action1 action, Action1 error) {
        ApplicationUtil.getInstance().isCommanding = true;
        if (BusinessUtil.checkTokenExpired(context)) {
            AuthTokenRequestEntity entity = BusinessUtil.createAuthTokenRequestEntity();
            AuthorService authorService = new AuthorService(context);
            authorService.pinReauthForNoPin(entity)
                    .subscribeOn(new AppScheduler().backgroundThread())
                    .observeOn(new AppScheduler().mainThread())
                    .subscribe(action, error);
        } else {
            Observable.create(new Observable.OnSubscribe<Object>() {
                @Override
                public void call(rx.Subscriber<? super Object> subscriber) {
                    subscriber.onNext(new Object());
                }
            }).subscribe(action, error);
        }
    }

}
